package cn.yeziji.file.aspect;

import cn.yeziji.file.annotation.Auth;
import cn.yeziji.file.service.InteractionService;
import cn.yeziji.forum.common.enums.ForumCommonStatus;
import cn.yeziji.forum.exception.ForumException;
import cn.yeziji.forum.utils.UserOnlineUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 请求 token 校验
 *
 * @author gzkemays
 * @since 2022/5/16 14:54
 */
@Component
@Aspect
@Slf4j
public class TokenAspect {
  @Resource HttpServletRequest request;
  @Resource InteractionService interactionService;

  @Around("@annotation(auth)")
  public Object doAfter(ProceedingJoinPoint pjp, Auth auth) {
    String header = auth.header();
    String attr = request.getHeader(header);
    if (!StringUtils.isBlank(attr)) {
      if (header.equals(HttpHeaders.AUTHORIZATION)) {
        if (!interactionService.checkToken(attr)) {
          throw new ForumException(ForumCommonStatus.TOKEN_ERROR);
        } else {
          UserOnlineUtils.setToken(attr);
        }
      } else if (header.equals("admin")) {
        if (!attr.equals("gzkemays")) {
          throw new ForumException(ForumCommonStatus.TOKEN_ERROR);
        }
      }
    } else {
      throw new ForumException(ForumCommonStatus.LOGIN_NULL);
    }
    try {
      return pjp.proceed();
    } catch (Throwable e) {
      throw new RuntimeException(e);
    } finally {
      UserOnlineUtils.clear();
    }
  }
}
